const readline = require('readline');
const CrawlerScheduler = require('./scheduler');
const fs = require('fs');
const path = require('path');
const moment = require('moment');

/**
 * 百度热搜爬虫命令行界面
 */
class CrawlerCLI {
  constructor() {
    this.scheduler = new CrawlerScheduler();
    this.rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
  }

  /**
   * 显示欢迎信息
   */
  showWelcome() {
    console.log('\n=================================================');
    console.log('             百度热搜爬虫 - 命令行界面');
    console.log('=================================================\n');
  }

  /**
   * 显示主菜单
   */
  showMainMenu() {
    console.log('\n请选择操作:');
    console.log('1. 立即爬取百度热搜');
    console.log('2. 查看最新热搜数据');
    console.log('3. 查看历史热搜数据');
    console.log('4. 启动定时爬取任务');
    console.log('5. 停止定时爬取任务');
    console.log('6. 配置设置');
    console.log('0. 退出程序');
    
    this.rl.question('\n请输入选项编号: ', (answer) => {
      switch (answer.trim()) {
        case '1':
          this.crawlNow();
          break;
        case '2':
          this.showLatestHotSearch();
          break;
        case '3':
          this.showHistoryList();
          break;
        case '4':
          this.startSchedule();
          break;
        case '5':
          this.stopSchedule();
          break;
        case '6':
          this.configSettings();
          break;
        case '0':
          this.exit();
          break;
        default:
          console.log('无效的选项，请重新选择');
          this.showMainMenu();
      }
    });
  }

  /**
   * 立即爬取百度热搜
   */
  async crawlNow() {
    console.log('\n正在爬取百度热搜，请稍候...');
    
    try {
      const result = await this.scheduler.manualCrawl();
      
      if (result.success) {
        console.log(`\n成功爬取 ${result.data.length} 条热搜`);
        console.log(`数据已保存到: ${result.savedFiles.txtPath}`);
        
        // 显示热搜数据
        this.displayHotSearchData(result.data);
      } else {
        console.log(`\n爬取失败: ${result.message}`);
      }
    } catch (error) {
      console.error(`爬取出错: ${error.message}`);
    }
    
    this.showMainMenu();
  }

  /**
   * 查看最新热搜数据
   */
  async showLatestHotSearch() {
    const latestData = this.scheduler.getLatestHotSearch();
    
    if (latestData.success) {
      console.log('\n最新百度热搜榜:');
      this.displayHotSearchData(latestData.data);
    } else {
      console.log(`\n获取最新热搜失败: ${latestData.message}`);
    }
    
    this.showMainMenu();
  }

  /**
   * 显示热搜数据
   */
  displayHotSearchData(data) {
    if (!data || data.length === 0) {
      console.log('暂无热搜数据');
      return;
    }
    
    console.log('\n--------------------------------------------');
    console.log(`更新时间: ${moment(data[0].timestamp).format('YYYY-MM-DD HH:mm:ss')}`);
    console.log('--------------------------------------------');
    
    data.forEach((item, index) => {
      const rank = item.rank || (index + 1);
      const title = item.title;
      const hotValue = item.hotValue ? ` (${item.hotValue})` : '';
      const hot = item.isHot ? ' [热]' : '';
      const newMark = item.isNew ? ' [新]' : '';
      
      console.log(`${rank}. ${title}${hotValue}${hot}${newMark}`);
    });
    
    console.log('--------------------------------------------');
  }

  /**
   * 查看历史热搜数据
   */
  showHistoryList() {
    const historyData = this.scheduler.getHistoryData();
    
    if (historyData.length === 0) {
      console.log('\n暂无历史数据');
      this.showMainMenu();
      return;
    }
    
    console.log('\n历史热搜数据:');
    
    // 按日期分组显示
    let currentDate = '';
    historyData.forEach((item, index) => {
      if (item.date !== currentDate) {
        if (currentDate !== '') {
          console.log('');
        }
        currentDate = item.date;
        console.log(`\n${currentDate}:`);
      }
      
      console.log(`  ${index + 1}. ${item.time.replace(/-/g, ':')}`);
    });
    
    this.rl.question('\n请输入要查看的历史数据编号(输入0返回主菜单): ', async (answer) => {
      const index = parseInt(answer.trim());
      
      if (index === 0) {
        this.showMainMenu();
        return;
      }
      
      if (isNaN(index) || index < 1 || index > historyData.length) {
        console.log('无效的编号');
        this.showHistoryList();
        return;
      }
      
      const item = historyData[index - 1];
      
      try {
        const data = JSON.parse(fs.readFileSync(item.filePath, 'utf8'));
        console.log(`\n${item.date} ${item.time.replace(/-/g, ':')} 的热搜数据:`);
        this.displayHotSearchData(data);
      } catch (error) {
        console.error(`读取历史数据失败: ${error.message}`);
      }
      
      this.showHistoryList();
    });
  }

  /**
   * 启动定时爬取任务
   */
  startSchedule() {
    const defaultCron = this.scheduler.config.cronExpression || '*/3 * * * *';
    
    this.rl.question(`\n请输入定时表达式 (默认为 "${defaultCron}"): `, (cronExpression) => {
      const cron = cronExpression.trim() || defaultCron;
      
      try {
        const started = this.scheduler.startSchedule(cron);
        
        if (started) {
          console.log(`定时爬取任务已启动，调度: ${cron}`);
          
          // 更新配置
          if (cron !== defaultCron) {
            this.scheduler.updateConfig({ cronExpression: cron });
          }
        } else {
          console.log('定时爬取任务已在运行中');
        }
      } catch (error) {
        console.error(`启动定时任务失败: ${error.message}`);
      }
      
      this.showMainMenu();
    });
  }

  /**
   * 停止定时爬取任务
   */
  stopSchedule() {
    const stopped = this.scheduler.stopSchedule();
    
    if (stopped) {
      console.log('\n定时爬取任务已停止');
    } else {
      console.log('\n没有运行中的定时任务');
    }
    
    this.showMainMenu();
  }

  /**
   * 配置设置
   */
  configSettings() {
    const config = this.scheduler.config;
    
    console.log('\n当前配置:');
    console.log(`1. 定时表达式: ${config.cronExpression || '*/3 * * * *'}`);
    console.log(`2. 保留历史天数: ${config.saveHistoryDays || 7}`);
    console.log(`3. 启动时自动开始定时任务: ${config.autoStartSchedule !== false ? '是' : '否'}`);
    console.log('0. 返回主菜单');
    
    this.rl.question('\n请选择要修改的配置项(0-3): ', (answer) => {
      const option = parseInt(answer.trim());
      
      switch (option) {
        case 1:
          this.rl.question('请输入新的定时表达式: ', (cron) => {
            if (cron.trim()) {
              this.scheduler.updateConfig({ cronExpression: cron.trim() });
              console.log('定时表达式已更新');
            }
            this.configSettings();
          });
          break;
        case 2:
          this.rl.question('请输入保留历史天数: ', (days) => {
            const daysNum = parseInt(days.trim());
            if (!isNaN(daysNum) && daysNum > 0) {
              this.scheduler.updateConfig({ saveHistoryDays: daysNum });
              console.log('保留历史天数已更新');
            } else {
              console.log('请输入有效的天数');
            }
            this.configSettings();
          });
          break;
        case 3:
          this.rl.question('启动时自动开始定时任务? (y/n): ', (answer) => {
            const autoStart = answer.trim().toLowerCase() === 'y';
            this.scheduler.updateConfig({ autoStartSchedule: autoStart });
            console.log('自动启动设置已更新');
            this.configSettings();
          });
          break;
        case 0:
          this.showMainMenu();
          break;
        default:
          console.log('无效的选项');
          this.configSettings();
      }
    });
  }

  /**
   * 退出程序
   */
  exit() {
    console.log('\n感谢使用百度热搜爬虫，再见！');
    this.rl.close();
    process.exit(0);
  }

  /**
   * 启动CLI
   */
  start() {
    this.showWelcome();
    
    // 显示定时任务状态
    if (this.scheduler.task) {
      console.log('定时爬取任务正在运行中');
    } else {
      console.log('定时爬取任务未启动');
    }
    
    // 尝试显示最新数据
    const latestData = this.scheduler.getLatestHotSearch();
    if (latestData.success) {
      this.displayHotSearchData(latestData.data);
    } else {
      console.log('暂无热搜数据，请使用"立即爬取"功能获取最新数据');
    }
    
    this.showMainMenu();
  }
}

module.exports = CrawlerCLI; 